package com.itheima.manager;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DateUtil;
import com.itheima.domain.db.User;
import com.itheima.domain.db.UserInfo;
import com.itheima.domain.mongo.Comment;
import com.itheima.domain.mongo.Movement;
import com.itheima.domain.mongo.UserState;
import com.itheima.service.db.UserInfoService;
import com.itheima.service.db.UserService;
import com.itheima.service.db.UserStateService;
import com.itheima.service.mongo.CommentService;
import com.itheima.service.mongo.MovementService;
import com.itheima.util.ConstantUtil;
import com.itheima.util.JwtUtil;
import com.itheima.vo.CommentVo;
import com.itheima.vo.MovementVo;
import com.itheima.vo.PageBeanVo;
import org.apache.dubbo.config.annotation.DubboReference;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Component;

import java.time.Duration;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@Component
public class UserManager {

    @DubboReference
    UserInfoService userInfoService;

    @DubboReference
    MovementService movementService;

    @DubboReference
    CommentService commentService;
    @DubboReference
    private UserStateService userStateService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @DubboReference
    private UserService userService;

    public ResponseEntity findByPage(Integer pageNum, Integer pageSize) {
        PageBeanVo pageBeanVo = userInfoService.findByPage(pageNum, pageSize);
        return ResponseEntity.ok(pageBeanVo);
    }

    public ResponseEntity findUserInfoById(Long userId) {
        UserInfo userInfo = userInfoService.findById(userId);
        return ResponseEntity.ok(userInfo);
    }

    public ResponseEntity findMovementByCondition4Page(Long userId, Integer state, Integer pageNum, Integer pageSize) {
        //0.若userId不为空,查询userInfo
        UserInfo userInfo = null;
        if (userId != null) {
            userInfo = userInfoService.findById(userId);
        }

        //1.远程调用service获取当前页数据pageBeanVo
        PageBeanVo pageBeanVo = movementService.findByCondition4Page(userId, state, pageNum, pageSize);

        //2.获取动态集合
        List<Movement> items = (List<Movement>) pageBeanVo.getItems();

        //3.遍历动态集合,获取每个动态,获取动态的发布人的userInfo,封装MovementVo,将每个vo放入voList
        List<MovementVo> voList = new ArrayList<>();

        if (CollUtil.isNotEmpty(items)) {
            for (Movement movement : items) {
                if (userInfo == null) {
                    userInfo = userInfoService.findById(movement.getUserId());
                }

                MovementVo vo = new MovementVo();

                vo.setUserInfo(userInfo);
                vo.setMovement(movement);

                //重新设置下时间
                vo.setCreateDate(DateUtil.formatDateTime(new Date(movement.getCreated())));

                voList.add(vo);
            }
        }

        //4.给pageBeanVo设置voList,且返回
        pageBeanVo.setItems(voList);
        return ResponseEntity.ok(pageBeanVo);
    }

    public ResponseEntity findMovementById(ObjectId movementId) {
        //查询movement
        Movement movement = movementService.findById(movementId);

        //查询userInfo
        UserInfo userInfo = userInfoService.findById(movement.getUserId());

        //封装vo
        MovementVo vo = new MovementVo();
        vo.setUserInfo(userInfo);
        vo.setMovement(movement);
        //重新设置下时间
        vo.setCreateDate(DateUtil.formatDateTime(new Date(movement.getCreated())));

        return ResponseEntity.ok(vo);
    }

    public ResponseEntity findMovementComemntByPage(String movementId, Integer pageNum, Integer pageSize) {
        //1.远程调用commentService查询评论信息(pageBeanVo)
        PageBeanVo pageBeanVo = commentService.findCommentByPage(new ObjectId(movementId), pageNum, pageSize, 2);

        //2.在pageBeanVo中获取评论list
        List<Comment> items = (List<Comment>) pageBeanVo.getItems();

        //3.遍历评论list
        List<CommentVo> voList = new ArrayList<>();

        if (CollUtil.isNotEmpty(items)) {
            items.forEach(comment -> {
                //4.获取每条评论的发布人userInfo,封装CommentVo,将每个vo放入voList中
                UserInfo userInfo = userInfoService.findById(comment.getUserId());

                CommentVo vo = new CommentVo();
                vo.setId(comment.getId().toString());
                vo.setAvatar(userInfo.getAvatar());
                vo.setNickname(userInfo.getNickname());
                vo.setContent(comment.getContent());
                vo.setCreateDate(DateUtil.formatDateTime(new Date(comment.getCreated())));

                // 将vo对象放入voList中
                voList.add(vo);
            });
        }

        //5.给pageBeanVo设置voList,且返回
        pageBeanVo.setItems(voList);
        return ResponseEntity.ok(pageBeanVo);
    }

    //动态拒绝
    public ResponseEntity movementStaterReject(String[] ids) {

        //调用service
        movementService.movementStaterReject(ids);
        return ResponseEntity.ok("动态拒绝");
    }

    //动态通过
    public ResponseEntity movementStaterPass(String[] ids) {
        //调用service
        movementService.movementStaterPass(ids);
        return ResponseEntity.ok("动态通过");
    }

    /**
     * 用户冻结
     * @param userState
     * @return
     */
    public ResponseEntity userFreeze(UserState userState) {
        // 1.先获取用户id
        Integer userId = userState.getUserId();
        // 2.获取用户信息
        UserInfo userInfo = userInfoService.findById(userId.longValue());
        Integer freezingRange = userState.getFreezingRange(); // 冻结范围
        Integer freezingTime = userState.getFreezingTime(); // 冻结时间
        //获取用户的登录范围 如果等于1的话就是冻结登录,就从redis中删除
        if (freezingRange == 1){ // 冻结登录
            // 获取用户
            User user = userService.findById(userInfo.getId());
            user.setPassword(null);
            String token = JwtUtil.createToken(BeanUtil.beanToMap(user));
            stringRedisTemplate.delete(ConstantUtil.USER_TOKEN+userInfo.getId()+token);
            // 判断冻结时间
            if (freezingTime == 1){
                // 冻结登录三天
                stringRedisTemplate.opsForValue().set("Free1"+userId,"1", Duration.ofDays(3));
            }
            if (freezingTime == 2){
                // 冻结登录7天
                stringRedisTemplate.opsForValue().set("Free1"+userId,"1", Duration.ofDays(7));
            }
            if (freezingTime == 3){
                // 冻结登录永久
                stringRedisTemplate.opsForValue().set("Free1"+userId,"1");
            }
        }
        // 冻结发言
        if (freezingRange == 2){
            if (freezingTime == 1){
                // 冻结发言三天
                stringRedisTemplate.opsForValue().set("Free2"+userId,"1",Duration.ofDays(3));
            }
            if (freezingTime == 2){
                // 冻结发言7天
                stringRedisTemplate.opsForValue().set("Free2"+userId,"1",Duration.ofDays(7));
            }
            if (freezingTime == 3){
                // 冻结发言永久
                stringRedisTemplate.opsForValue().set("Free2"+userId,"1");
            }
        }
        // 冻结动态
        if(freezingRange == 3) {
            if (freezingTime == 1) {
                //冻结发动态三天
                stringRedisTemplate.opsForValue().set("Free3"+userId, "1", Duration.ofDays(3));
            }
            if (freezingTime == 2) {
                //冻结发动态7天
                stringRedisTemplate.opsForValue().set("Free3"+userId, "1", Duration.ofDays(7));
            }
            if (freezingTime == 3) {
                //冻结发动态永久
                stringRedisTemplate.opsForValue().set("Free3"+userId, "1");
            }
        }
        userState.setId(ObjectId.get());
        // 保存
        userStateService.save(userState);
        // 修改用户的状态码为2冻结
        userInfo.setUserStatus("2");
        // 更新用户信息
        userInfoService.update(userInfo);
        return ResponseEntity.ok("已冻结!");
    }

    /**
     * 用户解冻
     * @param userId
     * @param reasonsForThawing
     * @return
     */
    public ResponseEntity userUnFreeze(long userId, String reasonsForThawing) {
        // 从冻结表中获取那条冻结记录
        UserState userState = userStateService.findByUserId(userId);
        // 判断
        if (userState != null){
            userState.setFreezingRange(0);
            userState.setFreezingTime(0);
            userState.setFrozenRemarks("已解冻");
            userState.setReasonsForFreezing(reasonsForThawing);
            userStateService.save(userState);
            // 获取当前用户的信息 修改状态
            UserInfo userInfo = userInfoService.findById(userId);
            userInfo.setUserStatus("1");
            // 修改
            userInfoService.update(userInfo);
            // 判断
            if (stringRedisTemplate.hasKey("Free1"+userId)){
                stringRedisTemplate.delete("Free1"+userId);
            }
            if (stringRedisTemplate.hasKey("Free2"+userId)){
                stringRedisTemplate.delete("Free2"+userId);
            }
            if (stringRedisTemplate.hasKey("Free3"+userId)){
                stringRedisTemplate.delete("Free3"+userId);
            }
            return ResponseEntity.ok("解冻完成!");
        }else {
            return ResponseEntity.ok("此用户未被冻结!");
        }

    }
}
